<template>
  <Form
    ref="formRef"
    v-loading="formLoading"
    :isCol="false"
    :rules="rules"
    :schema="allSchemas.formSchema"
    label-width="110px"
  >
    <!-- 先选择 -->
    <template #spuId>
      <el-button @click="openSelectGoods">选择商品 </el-button>
      <SkuList
        class="mt-20px"
        ref="skuListRef"
        :isComponent="false"
        :isDetail="false"
        :prop-form-data="spuData"
        :rule-config="ruleConfig"
      >
        <template #extension>
          <el-table-column
            align="center"
            label="折扣比例"
            v-if="sceneType == 'discount'"
            min-width="168"
          >
            <template #default="{ row }">
              <el-input
                v-model.number="row.productConfig.discount"
                :disabled="isDetail"
                :formatter="(value: string) => verifyNumberPercentage(value)"
                placeholder="请输入"
              >
                <template #append>
                  <span>%</span>
                </template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" label="数量" v-if="sceneType == 'number'" min-width="168">
            <template #default="{ row }">
              <el-input
                v-model.number="row.productConfig.discount"
                :disabled="isDetail"
                :formatter="(value: string) => verifiyNumberInteger(value)"
                placeholder="请输入"
              >
                <template #append>
                  <span>件</span>
                </template>
              </el-input>
            </template>
          </el-table-column>
        </template>
      </SkuList>
    </template>
  </Form>
  <GiveGoodsSelect ref="giveGoodsSelectRef" :isSelectSku="true" @confirm="selectSku" />
</template>
<script lang="ts" setup>
import { allSchemas, rules } from './GiveGoodsForm.data'
import { cloneDeep } from 'lodash-es'
import * as ProductSpuApi from '@/api/shop/product/spu'
import SkuList from '@/views/mall/product/components/SkuList.vue'
import { verifyNumberPercentage, verifiyNumberInteger } from '@/utils/formatter'

import GiveGoodsSelect from '../../components/GiveGoodsSelect.vue'
import { RuleConfig } from '@/views/mall/product/spu/components'
import { propTypes } from '@/utils/propTypes'
import { floatToFixed2 } from '@/utils'
defineOptions({ name: 'GiveGoodsForm' })
const props = defineProps({
  modelValue: propTypes.oneOfType<any>([]).isRequired,
  configType: propTypes.string.def(''), //规则类型
  sceneType: propTypes.string.def('discount'), //使用的场景类型
  isDetail: propTypes.bool.def(false),
  ruleConfig: propTypes.oneOfType<RuleConfig[]>([]) //规则
})
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formRef = ref() // 表单 Ref
const loading = ref(false)

// ================= 商品选择相关 =================

const giveGoodsSelectRef = ref() // 商品和属性选择 Ref
const openSelectGoods = () => {
  const selectedSkuIds = spuData.value.skus.map((ele) => {
    return ele.skuId
  })
  console.log(selectedSkuIds)
  giveGoodsSelectRef.value.open(selectedSkuIds)
}
const selectSku = (skuIds: number[]) => {
  getSkuDetails(skuIds)
}
/** 获取SKU详情 */
const spuData = ref({
  skus: []
}) //为了统一组件格式
const getSkuDetails = async (skuIds: number[] | undefined, products?: any) => {
  loading.value = true
  try {
    const data = await ProductSpuApi.getSkuPageList2({ skuIds } as any)
    if (data.list.length == 0) {
      return
    }
    console.log(spuData.value.skus)

    data.list?.forEach((sku) => {
      let config = { discount: 1 }
      if (props.sceneType == 'discount') {
        config.discount = 100
        const existData = spuData.value.skus.find((ele: any) => {
          return ele.skuId == sku.skuId
        })
        if (existData) {
          config.discount = existData?.productConfig?.discount
        }
        console.log(existData)
      }
      if (props.sceneType == 'number') {
        config.discount = 1
        const existData = spuData.value.skus.find((ele: any) => {
          return ele.skuId == sku.skuId
        })
        if (existData) {
          config.discount = existData?.productConfig?.discount
        }
        console.log(existData)
      }
      if (typeof products !== 'undefined') {
        const product = products.find((item) => item.skuId === sku.skuId)
        if (product) {
        }
        config = product.productConfig || config
      }
      sku.price = floatToFixed2(sku.price)
      sku.lowPrice = floatToFixed2(sku.lowPrice)
      sku.productConfig = config
      // ruleDataArr.value.forEach((element) => {
      //   if (element.skuId == sku.skuId) {
      //     sku.productConfig = element.productConfig
      //   }
      // })
    })
    spuData.value.skus = data.list
    console.log(spuData.value.skus)
  } finally {
    loading.value = false
  }
}

const objectToArray = (obj) => {
  return Object.keys(obj).map(function (key) {
    return { skuId: Number(key), productConfig: obj[key] }
  })
}
const arrayToObject = (arr) => {
  return arr.reduce(function (obj, item) {
    obj[item.skuId] = item.productConfig
    return obj
  }, {})
}
// getter
const hasRun = ref(false) // 标志位，用于控制监听器是否已执行

watch(
  () => props.modelValue,
  async (data) => {
    if (!data) return
    const products = objectToArray(data)
    if (products.length > 0) {
      if (!hasRun.value) {
        await getSkuDetails(
          products?.map((sku) => Number(sku.skuId)),
          products
        )
        hasRun.value = true
      }
    }
  },
  { immediate: true }
)

// setter

const emit = defineEmits(['update:modelValue', 'errorInfo'])

// ================= end =================
/**
 * 获取所有 sku 活动配置
 *
 * @param extendedAttribute 在 sku 上扩展的属性，例：秒杀活动 sku 扩展属性 productConfig 请参考 seckillActivity.ts
 */
const skuListRef = ref()
/** 提交表单 */
const validate = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.getElFormRef().validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    // 获取商品配置

    await skuListRef.value.validateSku()
    const products = cloneDeep(spuData.value.skus)
    let emitData = arrayToObject(products)
    emit('update:modelValue', emitData)
    // 如果校验通过 就表示没有错误信息
  } catch (e) {
    console.log(e)
    throw e

    // emit('errorInfo', e)
  } finally {
    formLoading.value = false
  }
}
defineExpose({ validate })
</script>
